package com.tomorrow.runner.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tomorrow.runner.R;
import com.tomorrow.runner.activity.basic.BasicActivity;
import com.tomorrow.runner.data.model.ActivityDataModel;
import com.tomorrow.runner.data.model.ActivityModel;
import com.tomorrow.runner.map.MapFragment;
import com.tomorrow.runner.share.ShareInfo;
import com.tomorrow.runner.share.ShareUtil;
import com.tomorrow.runner.util.Define;
import com.tomorrow.runner.util.TimeUitl;
import com.tomorrow.runner.util.WeatherUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.sucun.android.log.Log;
import cn.sucun.android.utils.DateUtils;

/**
 *
 * Created by tomorrow on 16-5-5.
 */
public class SportResultActivity extends BasicActivity implements View.OnClickListener {

    private static final String TAG = "SportResultActivity";
    private MapFragment mMapFragment;
    private EditText mEditTitle;
    private EditText mEditComment;

    private Button mBtnSave;

    private TextView mCountLabel;
    private TextView mDurationLabel;
    private TextView mCaloriesLabel;
    private TextView mMileLabel;
    private TextView mSpeedLabel;
    private TextView mStartTimeLabel;
    private TextView mEndTimeLabel;
    private ImageView mWeatherLabel;
    private TextView mPositionLabel;

    private ActivityModel mModel;
    private Map<Integer,ActivityDataModel> mDataModelMap;
    private int mType;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_result);
        initData();
        initUI();
        initMap();
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        int id = bundle.getInt(Define.KEY_ID);
        mType = bundle.getInt(Define.KEY_TYPE);
        mModel = getActivityModel(id);
        mDataModelMap = getActivityDataModelMap(id);
    }

    private void initUI() {
        mEditTitle = (EditText) findViewById(R.id.edit_title);
        mEditComment = (EditText) findViewById(R.id.edit_desc_content);

        mBtnSave = (Button) findViewById(R.id.btn_save);

        mCountLabel = (TextView) findViewById(R.id.label_count);
        mDurationLabel = (TextView) findViewById(R.id.label_duration);
        mCaloriesLabel = (TextView) findViewById(R.id.label_calories);
        mMileLabel = (TextView) findViewById(R.id.label_mile);
        mSpeedLabel = (TextView) findViewById(R.id.label_speed);
        mStartTimeLabel = (TextView) findViewById(R.id.label_start_time);
        mEndTimeLabel = (TextView) findViewById(R.id.label_end_time);
        mWeatherLabel = (ImageView) findViewById(R.id.label_weather);
        mPositionLabel = (TextView) findViewById(R.id.label_position);


        mEditTitle.setText(mModel.getString(ActivityModel.TITLE));
        mEditComment.setText(mModel.getString(ActivityModel.DESC_CONTENT));
        long start = mModel.getLong(ActivityModel.START_TIME);
        String startTime = DateUtils.formatDateString(start);
        mStartTimeLabel.setText(startTime);
        long end =mModel.getLong(ActivityModel.END_TIME);
        String endTime = DateUtils.formatDateString(end);
        mEndTimeLabel.setText(endTime);
        mWeatherLabel.setImageResource(WeatherUtil.getWeatherIconId(mModel.getString(ActivityModel.WEATHER)));
        mPositionLabel.setText(mModel.getString(ActivityModel.POSITION));

        int duration = (int) ((end - start)/1000);
        mDurationLabel.setText(TimeUitl.getTimeFormat(duration));
        if (mDataModelMap.get(ActivityDataModel.TYPE_CALORIE) != null){
            String c = mDataModelMap.get(ActivityDataModel.TYPE_CALORIE).getString(ActivityDataModel.PRIMARY_DATA);
            Double calories = Double.parseDouble(c);
            calories = calories / 1000;
            mCaloriesLabel.setText(calories+" 千卡");
        }

        if (mType == ActivityModel.TYPE_RUN){
            //run
            findViewById(R.id.row_count).setVisibility(View.GONE);
            if (mDataModelMap.get(ActivityDataModel.TYPE_AVG_SPEED) != null){
                String speed = mDataModelMap.get(ActivityDataModel.TYPE_AVG_SPEED).getString(ActivityDataModel.PRIMARY_DATA);
                mSpeedLabel.setText(speed+" 米/秒");
            }
            if (mDataModelMap.get(ActivityDataModel.TYPE_MILE) != null){
                String mile = mDataModelMap.get(ActivityDataModel.TYPE_MILE).getString(ActivityDataModel.PRIMARY_DATA);
                mMileLabel.setText(mile+" 米");
            }
        }
        if (mType == ActivityModel.TYPE_PUSH_UP){
            //pushup
            findViewById(R.id.row_mile).setVisibility(View.GONE);
            findViewById(R.id.row_speed).setVisibility(View.GONE);
            if (mDataModelMap.get(ActivityDataModel.TYPE_BASE_COUNT) != null){
                String count = mDataModelMap.get(ActivityDataModel.TYPE_BASE_COUNT).getString(ActivityDataModel.PRIMARY_DATA);
                mCountLabel.setText(count+" 个");
            }
        }

        mBtnSave.setOnClickListener(this);
    }

    private void initMap() {
        mMapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map_area);
        if (mType == ActivityModel.TYPE_RUN){
            ActivityDataModel dataModel = mDataModelMap.get(ActivityDataModel.TYPE_POSITION_POINT);
            if (dataModel == null){
                return;
            }
            String dataText = dataModel.getString(ActivityDataModel.PRIMARY_DATA);
            Bundle dataBundle = new Bundle();
            dataBundle.putString(Define.KEY_DATA,dataText);
            mMapFragment.setUpMapIfNeeded(MapFragment.SetupModel.ShowTrack,dataBundle);
        }else{
            if (mMapFragment.getView() != null){
                mMapFragment.getView().setVisibility(View.GONE);
            }
        }
    }

    private Map<Integer,ActivityDataModel> getActivityDataModelMap(int id){
        Map<Integer,ActivityDataModel> dataModelMap = new HashMap<>();
        String sql = ActivityDataModel.ACTIVITY_ID+"=" + id;
        Cursor cursorData = getContentResolver().query(ActivityDataModel.getContentUri(), null, sql, null, null);
        if (cursorData != null && cursorData.getCount() > 0){
            for (cursorData.moveToFirst();!cursorData.isAfterLast();cursorData.moveToNext()){
                ActivityDataModel data = new ActivityDataModel(cursorData);
                Log.i(TAG,"type="+data.getInt(ActivityDataModel.DATA_TYPE));
                dataModelMap.put(data.getInt(ActivityDataModel.DATA_TYPE),data);
            }
            cursorData.close();
        }
        return dataModelMap;
    }

    private ActivityModel getActivityModel(int id){
        ActivityModel model = null;
        String sql = ActivityModel._ID+"="+id;
        Cursor cursor = getContentResolver().query(ActivityModel.getContentUri(), null, sql, null, null);
        if (cursor != null && cursor.getCount() > 0){
            if (cursor.moveToFirst()){
                model = new ActivityModel(cursor);
            }
            cursor.close();
        }
        return model;
    }

    @Override
    public void onClick(View v) {
        String title = mEditTitle.getText().toString();
        String comment = mEditComment.getText().toString();
        if (!TextUtils.isEmpty(title)){
            mModel.setString(ActivityModel.TITLE,title);
        }
        if (!TextUtils.isEmpty(comment)){
            mModel.setString(ActivityModel.DESC_CONTENT,comment);
        }
        mModel.commitChange(getContentResolver());
        showMsgToast("保存成功");
        View view = findViewById(R.id.sport_result);
        String fileName = ShareUtil.saveFile(ShareUtil.getViewBitmap(view));
        File file = new File(fileName);
        ShareInfo shareInfo = new ShareInfo(title,null);
        if (file.exists()){
            shareInfo.setFile(Uri.fromFile(file));
        }
        ShareUtil.shareSomething(this,shareInfo);
    }
}
